﻿"""
Aura Audio Engine.
Derived from Conch, which is a file part of Ardentryst.
Thanks to Jordan Trudgett, author of Ardentryst, and his friends, family and associates,
who lent him their support with his project.
"""
import pygame

def engineinit(hz):
    try:
        pygame.mixer.init(hz, -16, 2, 2**10)
        i = list(pygame.mixer.get_init())
        if i[1] < 0:
            i[1] = "16, signed"
        else:
            i[1] = "16, unsigned"
    except Exception, e:
        print "Warning: Sound disabled! ("+str(e)+")"
        print "Is your sound in use?"

class System:
    def __init__(self):
        self.music={}
        self.sound={}
        self.mqueue=[]
        self.squeue=[]
        self.music_volume=100
        self.sound_volume=100

    def load_music(self,music,key):
        self.music[key]=music

    def load_sound(self,sound,key):
        self.music[key]=pygame.mixer.Sound(sound)

    def play_music(self,key):
        pygame.mixer.music.load(self.music[key])
        pygame.mixer.music.play()

    def play_sound(self,key,loops=0):
        self.music[key].play(loops)

    def stop_music(self,fade_time=0,new=None):
        if fade_time and new==None:
            pygame.mixer.music.fadeout(fade_time)
        elif fade_time and new != None and new != "next":
            pygame.mixer.music.fadeout(fade_time)
            self.play_music(new)
        elif fade_time and new != None and new=="next":
            pygame.mixer.music.fadeout(fade_time)
            self.play_music(self.mqueue.pop())
        else:
            pygame.mixer.music.stop()

    def stop_sound(self):
        pygame.mixer.music.stop()

    def set_music_volume(self,percent,fade=False,change_speed=40):
        music=pygame.mixer.music
        self.music_volume=music.get_volume()*100
        if fade:
            if self.music_volume>percent:
                while self.music_volume>percent:
                    self.music_volume-=1
                    music.set_volume(self.music_volume/100)
                    pygame.time.delay(1000/change_speed)
            elif self.music_volume<percent:
                while self.music_volume<percent:
                    self.music_volume+=1
                    music.set_volume(self.music_volume/100)
                    pygame.time.delay(1000/change_speed)
        else:
            music.set_volume(self.music_volume/100)